﻿import cgi
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.api import users
from entities import *
from Entities import *


def Add(userName,fullName,email,mobile,roleID):
    role = Entities.Role.get_by_id(roleID)
    users = db.GqlQuery("SELECT * FROM User WHERE UserName = :1",userName)
    if users.count() == 0:
        
        users = User(UserName = userName,FullName = fullName,Email = email,Mobile = mobile,RoleID = role)
        users.put()
        return "Complete"
        
    else:
        return "Duplicate"
        
def GetbyRole(RoleID):
    role = Entities.Role.get_by_id(RoleID)
    user_list = []
    users = User.gql('WHERE RoleID = :1',role)
    for user in users:
        user_dict = {}
        user_dict["UserID"] = user.key().id()
        user_dict["FullName"] = user.FullName
        user_dict["Email"] = user.Email
        user_dict["Mobile"] = user.Mobile
        user_list.append(user_dict)
    tuple_user = tuple(user_list)
    return tuple_user 

def Update(UserName,UserID,FullName,Email,Mobile,RoleID):
    user_update = User.get_by_id()
    role = Role.get_by_id(RoleID)
    user = db.GqlQuery("SELECT * FROM User WHERE FullName = :1 AND RoleID = :2",FullName,role)
    if user.count() == 0:
        user_update.UserName = UserName
        user_update.FullName = FullName
        user_update.Email = Email
        user_update.Mobile = Mobile
        user_update.RoleID = role
        user_update.put()
        return "Complete"
    else:
        return "Duplicate"
        
def Delete(UserName):
    user = db.GqlQuery("SELECT * FROM User WHERE UserName = :1",UserName)
    if user.count() > 0:
        User.delete(user)
        return "Complete"
    else:
        return "No .. "
        
def GetID(userName):
    users = Entities.User.gql('WHERE UserName = :1',userName)
    if users.count() != 0:
        for user in users:
            userID = user.key().id()
    else:
        userID = None
    return userID
        

